import os
from typing import List
from pydantic import BaseSettings, validator


class Settings(BaseSettings):
    """系统配置类"""
    
    # 基础设置
    APP_NAME: str = "美申智控系统"
    VERSION: str = "1.0.0"
    DEBUG: bool = False
    SECRET_KEY: str = "your-secret-key-change-in-production"
    
    # 服务器配置
    HOST: str = "0.0.0.0"
    PORT: int = 8000
    SERVER_ID: str = "meishen-server-001"
    
    # 跨域配置
    ALLOWED_HOSTS: List[str] = ["*"]
    
    # 数据库配置
    DATABASE_URL: str = "mysql+pymysql://username:password@localhost:3306/meishen_db"
    DATABASE_ECHO: bool = False
    
    # Redis配置
    REDIS_URL: str = "redis://localhost:6379/0"
    REDIS_PASSWORD: str = ""
    
    # MQTT配置
    MQTT_HOST: str = "mqtt.example.com"
    MQTT_PORT: int = 1883
    MQTT_USERNAME: str = ""
    MQTT_PASSWORD: str = ""
    MQTT_USE_TLS: bool = False
    MQTT_KEEPALIVE: int = 60
    
    # JWT配置
    JWT_SECRET_KEY: str = "your-jwt-secret-key"
    JWT_ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    REFRESH_TOKEN_EXPIRE_DAYS: int = 30
    
    # 安全配置
    PASSWORD_MIN_LENGTH: int = 6
    PASSWORD_HASH_ALGORITHM: str = "bcrypt"
    
    # 文件上传配置
    UPLOAD_DIR: str = "./uploads"
    MAX_UPLOAD_SIZE: int = 10 * 1024 * 1024  # 10MB
    ALLOWED_UPLOAD_EXTENSIONS: List[str] = [".jpg", ".jpeg", ".png", ".gif", ".mp4", ".mp3"]
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "./logs/app.log"
    LOG_MAX_SIZE: int = 100 * 1024 * 1024  # 100MB
    LOG_BACKUP_COUNT: int = 5
    
    # 设备配置
    DEVICE_HEARTBEAT_TIMEOUT: int = 300  # 5分钟
    DEVICE_OFFLINE_TIMEOUT: int = 600    # 10分钟
    SENSOR_DATA_RETENTION_DAYS: int = 90  # 90天
    
    # 告警阈值配置
    PAPER_LOW_THRESHOLD: int = 20        # 纸巾低阈值 20%
    SOAP_LOW_THRESHOLD: int = 15         # 洗手液低阈值 15%
    WASTE_HIGH_THRESHOLD: int = 80       # 污物高阈值 80%
    WATER_LOW_THRESHOLD: int = 20        # 水箱低阈值 20%
    BATTERY_LOW_THRESHOLD: int = 20      # 电池低阈值 20%
    TEMPERATURE_HIGH_THRESHOLD: int = 40  # 高温阈值 40°C
    HUMIDITY_HIGH_THRESHOLD: int = 85     # 高湿度阈值 85%
    
    # 工单配置
    WORK_ORDER_AUTO_ASSIGN: bool = True  # 自动分配工单
    WORK_ORDER_SLA_HOURS: int = 24       # SLA时间 24小时
    
    # 通知配置
    EMAIL_ENABLED: bool = False
    SMS_ENABLED: bool = True
    WEBHOOK_ENABLED: bool = True
    
    # 第三方服务配置
    TENCENT_MAP_API_KEY: str = ""        # 腾讯地图API密钥
    AMAP_API_KEY: str = ""               # 高德地图API密钥
    SMS_API_KEY: str = ""                # 短信服务API密钥
    
    @validator("ALLOWED_HOSTS", pre=True)
    def assemble_cors_origins(cls, v):
        """处理CORS origins配置"""
        if isinstance(v, str):
            return [i.strip() for i in v.split(",")]
        return v
    
    @validator("DATABASE_URL", pre=True)
    def assemble_db_connection(cls, v, values):
        """组装数据库连接字符串"""
        if isinstance(v, str):
            return v
        return f"mysql+pymysql://{v.get('username')}:{v.get('password')}@{v.get('host')}:{v.get('port')}/{v.get('database')}"
    
    class Config:
        env_file = ".env"
        case_sensitive = True


# 创建全局配置实例
settings = Settings()